package com.wsoft.core.utils;

import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.baomidou.mybatisplus.annotation.TableName;
import com.baomidou.mybatisplus.core.config.GlobalConfig;
import com.baomidou.mybatisplus.core.toolkit.GlobalConfigUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.wsoft.core.exception.Asserts;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSessionFactory;

/**
 * 数据库名称获取
 *
 * @Author zhonglj
 * @Date 2025/2/25 14:14
 */
public class TableNameUtils {
    /**
     * 获取实体类对应的数据库表名
     *
     * @param entityClass
     * @return java.lang.String
     * @author zhonglj
     * @date 2025/2/25 14:35
     **/
    public static String getTableName(Class<?> entityClass) {
        // 1. 优先读取@TableName注解
        TableName tableNameAnnotation = entityClass.getAnnotation(TableName.class);
        if (tableNameAnnotation != null) {
            return handleGlobalConfig(tableNameAnnotation.value());
        }

        // 2. 无注解时自动转换（驼峰转下划线）
        String className = entityClass.getSimpleName();
        String tableName = StringUtils.camelToUnderline(className);

        // 3. 处理全局表前缀配置
        return handleGlobalConfig(tableName);
    }

    /**
     * 处理全局表名前缀配置
     *
     * @param tableName
     * @return java.lang.String
     * @author zhonglj
     * @date 2025/2/25 14:27
     **/
    private static String handleGlobalConfig(String tableName) {
        GlobalConfig.DbConfig dbConfig = GlobalConfigUtils.getGlobalConfig(
                getMybatisConfiguration()
        ).getDbConfig();

        // 拼接表前缀（如配置了tablePrefix）
        return StrUtil.isNotBlank(dbConfig.getTablePrefix())
                ? dbConfig.getTablePrefix() + tableName
                : tableName;
    }

    public static Configuration getMybatisConfiguration() {
        SqlSessionFactory factory = SpringUtil.getBean(SqlSessionFactory.class);
        if (factory == null) {
            Asserts.fail("SqlSessionFactory Bean 未注册");
        }
        return factory.getConfiguration();
    }
}
